package com.cpr.core.rabbitmq.client.publishercofirms;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

/**
 * @author Chen Panrui
 * created at 2022/3/16 15:49
 *
 * waitForConfirmsOrDie方法 Broker端在返回nack(Basic.Nack)之后该方法会抛出java.io.IOException
 *
 * 这种方式是同步等待 ack的方式
 *
 */
public class ProducerPublisherConfirmsAsyncWait {
    public static void main(String[] args) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        // 指定协议 用户名+密码+host+端口号+虚拟主机
        factory.setUri("amqp://admin:123456@106.13.89.7:5672/%2f");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        // 当前通道标记为 发送方确认机制的通道
        channel.confirmSelect();

        channel.queueDeclare("queue.ppc", true, false, false, null);
        channel.exchangeDeclare("ex.ppc", BuiltinExchangeType.DIRECT, true, false, null);
        channel.queueBind("queue.ppc", "ex.ppc", "key.ppc");

        channel.basicPublish("ex.ppc", "key.ppc", null, "hello".getBytes(StandardCharsets.UTF_8));

        try {
            // 同步等待 消息的ack确认
            channel.waitForConfirmsOrDie(5000);
            System.out.println("发送的消息已经得到确认");
        } catch (IOException ex){
            System.out.println("消息被拒绝");
        } catch (IllegalStateException ex){
            System.out.println("发送的消息不是PublisherConfirm通道");
        } catch (TimeoutException ex){
            System.out.println("消息处理超时");
        }
        channel.close();
        connection.close();
    }
}
